<?php
declare (strict_types = 1);

namespace app\api\controller;
use app\model\BookChaptersModel;
use app\model\BookContentsModel;
use app\model\BookShelvesModel;
use app\model\BooksModel;
use app\model\RedisModel;
use app\model\UserModel;
use app\model\UserReadingRecordsModel;
use app\model\UserSearchHistoryModel;
use think\App;

class Books extends Base {

    private $model;
    private $bookChaptersModel;
    private $bookContentsModel;
    private $userSearchHistoryModel;
    private $bookShelvesModel;
    private $userReadingRecordsModel;

    private $userModel;

    public $cacheKey="book:id:";

    private $userCacheKey="user:";
    private $req;
    private $uid;
    private $page;
    private $limit = 20;


    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->req = request()->param();

        $this->page = isset($this->req['page']) ? $this->req['page']  : 1;

        $this->limit = isset($this->req['limit']) ? $this->req['limit']  : 10;

        $this->uid = $this->getUid();

        $this->model = new BooksModel();

        $this->bookChaptersModel = new BookChaptersModel();

        $this->bookContentsModel = new BookContentsModel();

        $this->userSearchHistoryModel = new UserSearchHistoryModel();

        $this->userReadingRecordsModel = new UserReadingRecordsModel();

        $this->bookShelvesModel = new BookShelvesModel();

        $this->userModel = new UserModel();
    }



    public function getBookList(){

        $where = [];
        $where[] = ["book_status","=",2];
        $where[] = ["is_delete","=",0];
        if(isset($this->req['word']) && !empty($this->req['word'])){
            $where[] = ['book_name|book_author','LIKE',"%{$this->req['word']}%"];


            if($this->uid ){
                //添加搜索记录
                $this->userSearchHistoryModel->addOne([
                    "uid"=>$this->uid,
                    "type"=>3,
                    "word"=>$this->req['word']
                ]);
            }
        }

        $list = $this->model->getList($where,$this->page,$this->limit,["created_at"=>"DESC","book_id"=>"ASC"]);

        foreach ($list as &$one){
            $one["is_shelves"] = $this->bookShelvesModel->getTotal(["uid"=>$this->uid,"s.book_id"=>$one["book_id"]]) > 0 ? true : false;
            $one["process"] = $this->model->getUserBookProcess($this->uid,$one["book_id"]);
        }


        $total = $this->model->getTotal($where);

        return $this->succData($total,$list);

    }



    /*
 * 猜你喜欢
 * */
    public function getGuessYouLike(){

        if(!isset($this->req['book_id']) || empty($this->req['book_id'])){
            return $this->fail("书籍Id不能为空");
        }
        $where = [];
        $where[] = ["book_status","=",2];
        $where[] = ["is_delete","=",0];
        $where[] = ["book_id","<>",$this->req['book_id']];

        $list = $this->model->getGuessList($where,$this->page,$this->limit,["created_at"=>"DESC","book_id"=>"ASC"]);

        foreach ($list as &$one){
            $one["is_shelves"] = $this->bookShelvesModel->getTotal(["uid"=>$this->uid,"s.book_id"=>$one["book_id"]]) > 0 ? true : false;
            $one["process"] = $this->model->getUserBookProcess($this->uid,$one["book_id"]);
        }


        $total = $this->limit ;

        return $this->succData($total,$list);
    }


    public function getBookInfo(){

        if(!isset($this->req['book_id']) || empty($this->req['book_id'])){
            return $this->fail("书籍Id不能为空");
        }

        $info = $this->model->getInfo($this->req['book_id']);

        if($info){
            $info["is_listen"] = (boolean)  $info["is_listen"];
            $info["is_shelves"] = $this->bookShelvesModel->getTotal(["uid"=>$this->uid,"s.book_id"=>$info["book_id"]]) > 0 ? true : false;
            $info["process"] = $this->model->getUserBookProcess($this->uid,$info["book_id"]);
        }


        return $this->succ($info);
    }


    public function getBookChaptersList(){

        if(!isset($this->req['book_id']) || empty($this->req['book_id'])){
            return $this->fail("书籍Id不能为空");
        }

        $where =[];
        $where[] = ["book_id","=",$this->req['book_id']];

        $info = $this->bookChaptersModel->getList($where);

        return $this->succ($info);

    }


    public function getChaptersContent(){

        if(!isset($this->req['chapter_id']) || empty($this->req['chapter_id'])){
            return $this->fail("章节ID不能为空");
        }

        //计算连续阅读记录
        $yDay = date('Y-m-d',  strtotime('-1 day'));
        $yWhere =[];
        $yWhere[] = ["uid",'=',$this->uid];
        $yWhere[] = ["created_at","BETWEEN",[$yDay." 00:00:00",$yDay." 23:59:59"]];

        $tDay = date('Y-m-d');
        $tWhere =[];
        $tWhere[] = ["uid",'=',$this->uid];
        $tWhere[] = ["created_at","BETWEEN",[$tDay." 00:00:00",$tDay." 23:59:59"]];

        if($this->userReadingRecordsModel->getTotal($yWhere) > 0 && $this->userReadingRecordsModel->getTotal($tWhere) <= 0 ){
            $res = $this->userModel->incrUserFeild($this->uid,"cn_read_day", 1);
            $this->delUserCache($this->uid);
        }elseif ( $this->userReadingRecordsModel->getTotal($yWhere) == 0){
            $res = $this->userModel->updateUserInfo($this->uid,["cn_read_day"=>1]);
            $this->delUserCache($this->uid);
        }

        $data = $this->bookChaptersModel->getInfo($this->req['chapter_id']);
        
        if(!empty($data)){
            $info = $this->bookContentsModel->getChapterInfo($this->req['chapter_id']);
            $data["chapter_content"] = $info["chapter_content"];
        }

        return $this->succ($data);

    }


    //获取用户书架列表
    public function getBookShelvesList(){

        if(!$this->uid){
            return $this->noLogin();
        }

        $where =[];
        $where[] = ["s.uid","=",$this->uid];
        $where[] = ["b.is_delete","=",0];
        $where[] = ["b.book_status","=",2];
        if(isset($this->req['word']) && !empty($this->req['word'])){
            $where[] = ['b.book_name|b.book_author','LIKE',"%{$this->req['word']}%"];


            if($this->uid ){
                //添加搜索记录
                $this->userSearchHistoryModel->addOne([
                    "uid"=>$this->uid,
                    "type"=>4,
                    "word"=>$this->req['word']
                ]);
            }
        }

        $list = $this->bookShelvesModel->getList($where,$this->page,$this->limit,["s.updated_at"=>"DESC"]);

        $total = $this->bookShelvesModel->getTotal($where);

        $data = [];
        if(!empty($list)){
            foreach ($list as $item){
                $info = $this->model->getInfo($item["book_id"]);
                $info["is_shelves"] = $this->bookShelvesModel->getTotal(["uid"=>$this->uid,"s.book_id"=>$info["book_id"]]) > 0 ? true : false;
                $info["process"] = $this->model->getUserBookProcess($this->uid,$info["book_id"]);
                $data[] =$info;
            }
        }

        return $this->succData($total,$data);

    }



    /*
     * 把书籍添加到书架
     * */
    public function addBookShelves()
    {

        if(!$this->uid){
            return $this->noLogin();
        }

        if(!isset($this->req['book_id']) || empty($this->req['book_id'])){
            return $this->fail("书籍Id不能为空");
        }

        $bookInfo = $this->model->getInfo($this->req['book_id']);
        if(!$bookInfo){
            return $this->fail("书籍不存在");
        }

        if($bookInfo["is_delete"] == 1 || $bookInfo["book_status"] != 2){
            return $this->fail("书籍已下架");
        }


        $data = [
            'uid' => $this->uid,
            'book_id' => $this->req['book_id'],
        ];

        if($this->bookShelvesModel->getTotal( [
            'uid' => $this->uid,
            's.book_id' => $this->req['book_id'],
        ])){
            return $this->fail("书籍已存在书架中");
        }


        $res1 = $this->bookShelvesModel->addOne($data);

        $res2 = $this->model->incrBookField([$this->req['book_id']],"shelf_count");

        $this->delCache($this->req['book_id']);

        if($res1){
            return $this->succ();
        }else{
            return $this->fail();
        }

    }



    /*
     * 把书籍从书架中移除
     * */
    public function removeBookShelves()
    {

        if(!$this->uid){
            return $this->noLogin();
        }

        if(!isset($this->req['book_ids']) || empty($this->req['book_ids'])){
            return $this->fail("请选择要移除的书籍");
        }


        $where =[];
        $where[] = ["uid","=",$this->uid];
        $where[] = ["book_id","IN",$this->req['book_ids']];

        $res1 = $this->bookShelvesModel->delAll($where);

        $res2 = $this->model->decBookField($this->req['book_ids'],"shelf_count");


        foreach ($this->req['book_ids'] as $id){
            $this->delCache($id);
        }

        if($res1){
            return $this->succ();
        }else{
            return $this->fail();
        }

    }


    public function delUserCache($uid)
    {
        $redisModel = new RedisModel();

        return $redisModel->delete($this->userCacheKey.$uid);
    }


    public function delCache($id)
    {
        $redisModel = new RedisModel();

        return $redisModel->delete($this->cacheKey.$id);
    }


    public function delAllCache()
    {
        $redisModel = new RedisModel();

        return $redisModel->deleteAll($this->cacheKey);
    }
}
